package com.gudy.counter.util;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.gudy.counter.bean.*;
import com.gudy.counter.cache.RedisStringCache;
import com.gudy.counter.enumutil.CacheType;
import com.gudy.counter.thirdpaet.order.OrderCmd;
import com.gudy.counter.thirdpaet.order.OrderStatus;
import lombok.extern.log4j.Log4j2;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DBUtil {

    private static DBUtil dbUtil = null;
    public DBUtil(){

    }

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;




    //java注解在servlet启动的时候会调用一次通常用来进行初始化

    private  void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate){
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    private SqlSessionTemplate  getSqlSessionTemplate(){
        return this.sqlSessionTemplate;
    }

    @PostConstruct
    private  void init (){
        dbUtil = new DBUtil();
        dbUtil.setSqlSessionTemplate(this.sqlSessionTemplate);
    }

   //身份认证
    public static Account quertAccount(long uid, String password){
        return dbUtil.getSqlSessionTemplate().selectOne("userMapper.queryAccount",
                ImmutableMap.of("uid",uid,"password",password));
    }
    //更新登录信息
    public void updateLoginTime(long uid, String modifyDate, String modifyTime){
        dbUtil.getSqlSessionTemplate().update("userMapper.updateLoginTime",
                ImmutableMap.of("uid",uid,"modifydate",modifyDate,"modifytime",modifyTime));
    }
    //修改密码
    public boolean updatePassword(long uid,String oldPassword,String newPassword){
        int updateState = dbUtil.getSqlSessionTemplate().update("userMapper.updatePassword",
                ImmutableMap.of("uid", uid, "oldpassword", oldPassword, "newpassword", newPassword));
        if (updateState > 0){
            return true;
        }
        return false;
    }

    //资金类
    public static long queryBalance(long uid){
        long res = dbUtil.getSqlSessionTemplate().selectOne("orderMapper.queryBalance", ImmutableMap.of("uid", uid));
        if (res >= 0){
            return res;
        }
        return -1;
    }
    //持仓类
    public static List<PosiInfo> queryPosiInfo(long uid){
        //查询缓存如果不存在就去查找数据库
        try {
            String posiCache = RedisStringCache.queryCache(String.valueOf(uid), CacheType.POSI);
            if (StringUtils.isEmpty(posiCache)){
                List<PosiInfo> posiInfo = dbUtil.getSqlSessionTemplate().selectList("posiMapper.queryPosiInfo", ImmutableMap.of("uid", uid));
                if (posiInfo != null && posiInfo.size() > 0){
                    RedisStringCache.saveCache(String.valueOf(uid), JsonUtil.toJson(posiInfo), CacheType.POSI);
                    return posiInfo;
                }
            }else{
                return JsonUtil.fromJsonArr(posiCache,PosiInfo.class);
            }
        }catch (Exception e){
            //这里通常是记录日志的但是没有引入日志
            System.out.println("出现异常");
        }

        return null;
    }
    //委托类
    public static List<OrderInfo> queryOrderInfo(long uid){
        //查询缓存如果不存在就去查找数据库
        try {
            String orderCache = RedisStringCache.queryCache(String.valueOf(uid), CacheType.ORDER);
            if (StringUtils.isEmpty(orderCache)){
                List<OrderInfo> orderInfo = dbUtil.getSqlSessionTemplate().selectList("orderMapper.queryOrderInfo", ImmutableMap.of("uid", uid));
                if (orderInfo != null && orderInfo.size() > 0){
                    RedisStringCache.saveCache(String.valueOf(uid), JsonUtil.toJson(orderInfo), CacheType.POSI);
                    return orderInfo;
                }
            }else{
                return JsonUtil.fromJsonArr(orderCache,OrderInfo.class);
            }
        }catch (Exception e){
            //这里通常是记录日志的但是没有引入日志
            System.out.println("出现异常");
        }

        return null;
    }
    //成交类
    public static List<TradeInfo> queryTradeInfo(long uid){
        //查询缓存如果不存在就去查找数据库
        try {
            String tradeCache = RedisStringCache.queryCache(String.valueOf(uid), CacheType.TRADE);
            if (StringUtils.isEmpty(tradeCache)){
                List<TradeInfo> tradeInfo = dbUtil.getSqlSessionTemplate().selectList("tradeMapper.querytradeInfo", ImmutableMap.of("uid", uid));
                if (tradeInfo != null && tradeInfo.size() > 0){
                    RedisStringCache.saveCache(String.valueOf(uid), JsonUtil.toJson(tradeInfo), CacheType.POSI);
                    return tradeInfo;
                }
            }else{
                return JsonUtil.fromJsonArr(tradeCache,TradeInfo.class);
            }
        }catch (Exception e){
            //这里通常是记录日志的但是没有引入日志
            System.out.println("出现异常");
        }

        return null;
    }
    //股票查询类
   public static List<StockInfo> queryAllSotckInfo(){
        return dbUtil.getSqlSessionTemplate().selectList("stockMapper.queryAllSotckInfo");

   };

    ////订单处理类
    public static  int saveOrder(OrderCmd orderCmd){
        Map<String, Object> paramsMap = Maps.newHashMap();
        paramsMap.put("uid",orderCmd.uid);
        paramsMap.put("code",orderCmd.code);
        paramsMap.put("direction",orderCmd.direction.getDirection());
        paramsMap.put("type",orderCmd.type.getType());
        paramsMap.put("price",orderCmd.price);
        paramsMap.put("ocount",orderCmd.volume);
        paramsMap.put("tcount",0);
        paramsMap.put("status", OrderStatus.NOT_SET.getCode());
        paramsMap.put("date",TimeformatUtil.yyyyMMdd(orderCmd.timestamp));
        paramsMap.put("time",TimeformatUtil.hhMMss(orderCmd.timestamp));
        int status = dbUtil.getSqlSessionTemplate().insert("orderMapper.saveOrder",
                paramsMap);
        if (status > 0 ){
            OrderTotalInfo orderTotalInfo = dbUtil.getSqlSessionTemplate().selectOne("totalMapper.queryOrderbyUidAndCode", ImmutableMap.of("uid", orderCmd.uid, "code", orderCmd.code));
            if (orderTotalInfo == null){
                 dbUtil.getSqlSessionTemplate().insert("totalMapper.saveOrderTotal", paramsMap);
            }else{
                 dbUtil.getSqlSessionTemplate().update("totalMapper.updateOrderToal",ImmutableMap.of("ocount",(orderCmd.volume + orderTotalInfo.getOcount()),"code",orderCmd.code,"uid",orderCmd.uid));
            }
            return Integer.parseInt(paramsMap.get("id").toString());
        }
        return -1;
    }

    ////订单处理类
    public static  CounterRes saleOrder(OrderCmd orderCmd){
        Map<String, Object> paramsMap = Maps.newHashMap();
        paramsMap.put("uid",orderCmd.uid);
        paramsMap.put("code",orderCmd.code);
        paramsMap.put("direction",orderCmd.direction.getDirection());
        paramsMap.put("type",orderCmd.type.getType());
        paramsMap.put("price",orderCmd.price);
        paramsMap.put("ocount",orderCmd.volume);
        paramsMap.put("tcount",0);
        paramsMap.put("status", OrderStatus.NOT_SET.getCode());
        paramsMap.put("date",TimeformatUtil.yyyyMMdd(orderCmd.timestamp));
        paramsMap.put("time",TimeformatUtil.hhMMss(orderCmd.timestamp));
        int status = dbUtil.getSqlSessionTemplate().insert("orderMapper.savesaleOrder",
                paramsMap);
        if (status > 0 ){
            OrderTotalInfo orderTotalInfo = dbUtil.getSqlSessionTemplate().selectOne("totalMapper.queryOrderbyUidAndCode", ImmutableMap.of("uid", orderCmd.uid, "code", orderCmd.code));
            if (orderTotalInfo == null){
                return null;
            }else{
                dbUtil.getSqlSessionTemplate().update("totalMapper.updateOrderToal",ImmutableMap.of("ocount", ( orderTotalInfo.getOcount()-orderCmd.volume),"code",orderCmd.code,"uid",orderCmd.uid));
            }
            return new CounterRes(ConstCommon.SUCCESS,String.valueOf(status),orderTotalInfo.getOcount()-orderCmd.volume);
        }
        return  null;
    }



    //订单金额扣减类
    public static int updateBalance(long balance,long uid,String password){
        return dbUtil.getSqlSessionTemplate().update("userMapper.updateBalance", ImmutableMap.of("balance",balance,"uid", uid, "password", password));
    }
    //订单扣减库存
    public static int updateStockByAddordCount(long code,long addordCount){
        return dbUtil.getSqlSessionTemplate().update("orderMapper.updateStockByAddordCount", ImmutableMap.of("code",code,"addordCount", addordCount));
    }
    //最新的五笔订单交易
    public static List<OrderInfo> getAllOrder() {
        return dbUtil.getSqlSessionTemplate().selectList("orderMapper.getAllOrder");
    }
    //获取到总的订单数量
    public static  OrderTotalInfo queryOrderbyUidAndCode(long uid,int code){
        return dbUtil.getSqlSessionTemplate().selectOne("totalMapper.queryOrderbyUidAndCode", ImmutableMap.of("code",code,"uid", uid));
    }

    //获取到总的订单数量
    public static   List<OrderInfo> getAllSaleOrder(){
        return dbUtil.getSqlSessionTemplate().selectList("totalMapper.getAllSaleOrder");
    }

    //获取所有当日委托
    public static List<OrderInfo> queryOrderAndsaleOrder(String currentDate,long uid,String code,String startDate,String endDate,String status){
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("time",currentDate);
        paramMap.put("uid",uid);
        paramMap.put("code",code);
        paramMap.put("startdate",startDate);
        paramMap.put("enddate",endDate);
        paramMap.put("status",StringUtils.isEmpty(status) ? "":Integer.valueOf(status));


        return dbUtil.getSqlSessionTemplate().selectList("orderMapper.queryOrderAndsaleOrder",paramMap);
    }


    ////订单处理类
    public static  CounterRes saveTranSaction(Transaction transaction,String token){
        //这里可以调用跨行的逻辑
        int insert = dbUtil.getSqlSessionTemplate().insert("transactionMapper.saveTransaction", transaction);
        if (insert > 0){
            String accountInfo = RedisStringCache.queryCache(token, CacheType.ACCOUNT);
            Account account = JsonUtil.fromJson(accountInfo, Account.class);
            long  moneyCount = account.getBalance() + transaction.getMoney();
            account.setBalance(moneyCount);
            RedisStringCache.saveCache(token, JsonUtil.toJson(account),CacheType.ACCOUNT);
            updateBalance(moneyCount,account.getUid(),account.getPassword());
            return new CounterRes(ConstCommon.SUCCESS,"账号充值成功",null);
        }

        return new CounterRes(ConstCommon.FALA,"账号充值失败",null);
    }
    public static CounterRes queryTransaction(String startDate, String endDate, String uid) {
        HashMap<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("startDate",startDate);
        paramMap.put("endDate",endDate);
        paramMap.put("uid",uid);
        return new CounterRes(ConstCommon.SUCCESS,"查询成功",dbUtil.getSqlSessionTemplate().selectList("transactionMapper.queryTransaction", paramMap));
    }
}
